package tms.business.mail;

import tms.business.notification.NotificationBroker;
import tms.business.notification.NotificationMethod;
import tms.business.notification.NotifyBy;
import tms.model.login.UserEntity;
import tms.util.exception.ApplicationRuntimeException;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.enterprise.context.ApplicationScoped;
import javax.jms.*;
import java.util.ArrayList;
import java.util.List;


@NotifyBy(NotificationMethod.EMAIL)
@ApplicationScoped
public class EmailNotificationBroker implements NotificationBroker {
    @Resource(name="TmsNotificationsFactory")
    private ConnectionFactory connectionFactory;
    @Resource(name="TmsNotificationsQueue")
    private Destination destination;

    private Connection connection;


    public void notifyUsers(List<UserEntity> users) {
        if (!users.isEmpty()) {
            try {
                Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
                MessageProducer producer = session.createProducer(destination);
                ObjectMessage message = session.createObjectMessage();
                message.setObject(new ArrayList<UserEntity>(users));

                producer.send(message);

                session.close();
            } catch (JMSException e) {
                e.printStackTrace();
                throw new ApplicationRuntimeException(e);
            }
        }
    }


    @PostConstruct
    private void initJmsConnection() {
        try {
            connection = connectionFactory.createConnection();
        } catch (JMSException e) {
            e.printStackTrace();
            throw new ApplicationRuntimeException(e);
        }
    }

    @PreDestroy
    public void destroy() {
        try {
            connection.close();
        } catch (JMSException e) {
            e.printStackTrace();
            throw new ApplicationRuntimeException(e);
        }
    }
}
